import { App, Modal, Plugin, Setting, Notice } from 'obsidian';

export class RenamingUI extends Modal {
  plugin: Plugin;
  heading: string;
  resolve: (
    value: string | undefined | PromiseLike<string | undefined>
  ) => void;

  constructor(app: App, plugin: Plugin, originHeading: string) {
    super(app);
    this.plugin = plugin;
    this.heading = originHeading;
  }

  open(): Promise<string> {
    super.open();
    return new Promise((resolve) => {
      this.resolve = resolve;
    });
  }

  onOpen() {
    const { contentEl, titleEl } = this;
    titleEl.setText("Input heading");
    const div = contentEl.createDiv();

    const text = div.createEl("input", {
      type: "text",
      text: this.heading,
      value: this.heading,
    });

    div.createEl("button", {
      text: "Save",
    }).addEventListener("click", async () => {
      // `this.resolve` asserts non-null here because the function is assigned when the `this.open()` is called
      // and is not null at the time the save button is clicked.
      this.resolve!(text.value);
      this.close();
    });
  }

  onClose() {
    const { contentEl } = this;
    // `this.resolve` asserts non-null here because the function is assigned when the `this.open()` is called
    // and is not null at the time the modal is closed.
    this.resolve!(undefined);
    contentEl.empty();
  }
}
